package com.netty4.http.xml;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

import java.net.InetSocketAddress;

public class HttpXmlClient {

    public void connect(int port)throws  Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true).handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new HttpResponseDecoder());
                    socketChannel.pipeline().addLast(new HttpObjectAggregator(65536));
                    socketChannel.pipeline().addLast(new HttpXmlResponseDecoder(Order.class,true));
                    socketChannel.pipeline().addLast(new HttpRequestEncoder());
                    socketChannel.pipeline().addLast(new HttpXmlRequestEncoder());
                    socketChannel.pipeline().addLast(new HttpXmlClientHandler());
                }
            });
            ChannelFuture sync = b.connect(new InetSocketAddress(port)).sync();
            sync.channel().closeFuture().sync();
        }catch (Exception e){
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        try {
            new HttpXmlClient().connect(8080);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
